package com.atung.parking.config.security;

import com.atung.parking.config.auth.entity.AuthUserEntity;
import com.atung.parking.enums.AdminType;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author wangbo
 * @since 2022/10/17 14:32
 */
@Component
public class JwtTokenUtil implements Serializable {


    private String tokenLocalNameConstant = "user:login";
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    private String secret = "wb1234567890";
    private Long expiration = 300000000L;
    private String header = "wb_header";

    private String generateToken(Map<String, Object> claims) {
        Date expirationDate = new Date(System.currentTimeMillis() + expiration);
        return Jwts.builder().setClaims(claims)
                .setExpiration(expirationDate)
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact().toString();
    }

    private Claims getClaimsFromToken(String token) {
        Claims claims;
        try {
            claims = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();

        } catch (Exception e) {
            claims = null;
        }
        return claims;
    }

    public String generateToken(AuthUserEntity userDetails, HttpServletRequest httpServletRequest) {
        Map<String, Object> claims = new HashMap<>(2);
        claims.put("id", userDetails.getUserId());
        claims.put("name", userDetails.getUsername());
        claims.put("created", new Date());
        claims.put("ipConfig", WebIpUtils.getIpAddress(httpServletRequest));
        claims.put("role", userDetails.getRoleType().ordinal());
        String token = generateToken(claims);
        stringRedisTemplate.opsForValue().set(tokenLocalNameConstant + userDetails.getUserId(), token);
        return token;
    }

    public void clearAuthUserEntity(AuthUserEntity userDetails) {
        stringRedisTemplate.delete(tokenLocalNameConstant + userDetails.getUserId());

    }

    public AuthUserEntity getAuthUserEntity(String token) {
        AuthUserEntity userDetails = new AuthUserEntity();
        try {
            Claims claims = getClaimsFromToken(token);
            String role = claims.get("role").toString();
            userDetails.setUsername(claims.get("name").toString());
            userDetails.setUserId(Long.valueOf(claims.get("id").toString()));
            userDetails.setRoleType(AdminType.fromCode(Integer.valueOf(role)));
            return userDetails;
        } catch (Exception e) {
            return null;
        }
    }


    public AdminType getRoleFromToken(String token) {
        try {
            Claims claims = getClaimsFromToken(token);
            String role = claims.get("role").toString();
            return AdminType.fromCode(Integer.valueOf(role));
        } catch (Exception e) {
            return null;
        }
    }

    public String getUsernameFromToken(String token) {
        String username;
        try {
            Claims claims = getClaimsFromToken(token);
            username = claims.get("id").toString();

        } catch (Exception e) {
            username = null;
        }
        return username;
    }

    public Boolean isTokenIp(String token, String ip) {
        try {
            Claims claims = getClaimsFromToken(token);
            String ipConfig = claims.get("ipConfig").toString();
            String role = claims.get("role").toString();
            if (String.valueOf(AdminType.USER.ordinal()).equals(role)) {
                return true;
            }
            if (ipConfig.equals(ip)) {
                return true;
            }
        } catch (Exception e) {
            return false;
        }
        return false;
    }

    public Boolean validateToken(String token, String ip) {
        String username = getUsernameFromToken(token);
        if (stringRedisTemplate.hasKey(tokenLocalNameConstant + username)
                &&
                stringRedisTemplate.opsForValue().get(tokenLocalNameConstant + username).equals(token)) {
            return this.isTokenIp(token, ip);
        }
        return false;
    }

}